import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'
import { constantRoutes } from '@/router/index'
import { resetRouter } from '@/router/index'

const state = {
  token: getToken(),
  userInfo: {}, // 保存用户信息
  routes: constantRoutes // 保存所有的路由 -- 默认只有静态路由
}
const mutations = {
  // 保存token
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  // 设置用户信息
  setUserInfo(state, user) {
    state.userInfo = user
  },
  // 设置路由
  setRoutes(state, routes) {
    state.routes = [...state.routes, ...routes]
  },
  // 清空路由
  removeRoutes(state) {
    state.routes = constantRoutes
  }
}
const actions = {
  // 登录
  async loginAsync(store, data) {
    // 调用接口 --- 后面再完成
    // 先假设token已经获取到了
    const token = await login(data)
    // console.log(token)
    store.commit('setToken', token)
  },
  async getUserInfo(store) {
    // 调用接口 获取用户信息
    const res = await getUserInfo()
    // console.log(res)
    store.commit('setUserInfo', res)
    return res
  },
  // 退出登录
  logout(store) {
    store.commit('removeToken')
    store.commit('setUserInfo', {})
    // 清空vuex中路由
    store.commit('removeRoutes')
    // 重置路由 ---
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
